// API 服务
import authService from './auth';

const API_BASE_URL = 'http://localhost:8080';

// 通用请求方法
const request = async (url, options = {}) => {
  try {
    // 获取当前用户ID - 从 Keycloak 获取
    const userId = authService.getUserId();
    
    console.log('API 请求: 当前用户 ID:', userId);
    
    // 准备请求体，如果是POST/PUT请求且有body，则添加userId
    let body = options.body ? JSON.parse(options.body) : {};
    if (['POST', 'PUT'].includes(options.method) && userId) {
      body.userId = userId;
      console.log('API 请求: 添加用户 ID 到请求体', userId);
    }
    
    // 如果是GET请求，将userId添加到URL参数中
    let finalUrl = url;
    if (options.method === 'GET' && userId) {
      const separator = url.includes('?') ? '&' : '?';
      finalUrl = `${url}${separator}userId=${userId}`;
      console.log('API 请求: 添加用户 ID 到 URL 参数', finalUrl);
    }
    
    // 准备最终的请求选项
    const finalOptions = {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        // 如果有认证令牌，添加到请求头
        ...(authService.getToken() ? { 'Authorization': `Bearer ${authService.getToken()}` } : {}),
        ...options.headers
      }
    };
    
    // 如果有请求体，更新它
    if (['POST', 'PUT'].includes(options.method)) {
      finalOptions.body = JSON.stringify(body);
    }

    const response = await fetch(`${API_BASE_URL}${finalUrl}`, finalOptions);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
};

// 项目组相关 API
export const projectGroupApi = {
  // 获取项目组列表
  getProjectGroups: async (page = 1, size = 10, name = '') => {
    return request(`/api/project-group/page?page=${page}&size=${size}${name ? `&groupName=${name}` : ''}`);
  },

  // 添加项目组
  addProjectGroup: async (projectGroup) => {
    return request('/api/project-group/add', {
      method: 'POST',
      body: JSON.stringify(projectGroup)
    });
  },

  // 更新项目组
  updateProjectGroup: async (projectGroup) => {
    return request('/api/project-group/update', {
      method: 'PUT',
      body: JSON.stringify(projectGroup)
    });
  },

  // 删除项目组
  deleteProjectGroup: async (id) => {
    return request(`/api/project-group/delete/${id}`, {
      method: 'DELETE'
    });
  },

  // 获取项目组详情
  getProjectGroup: async (id) => {
    return request(`/api/project-group/get/${id}`);
  }
};

// 项目相关 API
export const projectApi = {
  // 获取项目列表
  getProjects: async (page = 1, size = 10, projectName = '', groupId = null) => {
    let url = `/api/project/page?page=${page}&size=${size}`;
    if (projectName) url += `&projectName=${projectName}`;
    if (groupId) url += `&groupId=${groupId}`;
    return request(url);
  },

  // 添加项目
  addProject: async (project) => {
    return request('/api/project/add', {
      method: 'POST',
      body: JSON.stringify(project)
    });
  },

  // 更新项目
  updateProject: async (project) => {
    return request('/api/project/update', {
      method: 'PUT',
      body: JSON.stringify(project)
    });
  },

  // 删除项目
  deleteProject: async (id) => {
    return request(`/api/project/delete/${id}`, {
      method: 'DELETE'
    });
  },

  // 获取项目详情
  getProject: async (id) => {
    return request(`/api/project/get/${id}`);
  }
};

// 项目版本相关 API
export const projectVersionApi = {
  // 获取项目版本列表
  getProjectVersions: async (projectId, page = 1, size = 10) => {
    return request(`/api/project-version/page?projectId=${projectId}&page=${page}&size=${size}`);
  },

  // 添加项目版本
  addProjectVersion: async (version) => {
    return request('/api/project-version/add', {
      method: 'POST',
      body: JSON.stringify(version)
    });
  },

  // 更新项目版本
  updateProjectVersion: async (version) => {
    return request('/api/project-version/update', {
      method: 'PUT',
      body: JSON.stringify(version)
    });
  },

  // 删除项目版本
  deleteProjectVersion: async (id) => {
    return request(`/api/project-version/delete/${id}`, {
      method: 'DELETE'
    });
  },

  // 获取项目版本详情
  getProjectVersion: async (id) => {
    return request(`/api/project-version/get/${id}`);
  },
  
  // 获取项目最新版本
  getLatestProjectVersion: async (projectId) => {
    return request(`/api/project-version/latest?projectId=${projectId}`);
  }
};

// Kubernetes部署相关API
export const kubernetesApi = {
  // 通过YAML部署应用到Kubernetes
  deployYaml: async (yaml, namespace = 'default', projectId = null,releaseName = null) => {
    const requestBody = { yaml, namespace };
    if (projectId !== null) {
      requestBody.projectId = projectId;
    }
    if (releaseName !== null) {
      requestBody.releaseName = releaseName;
    }
    return request('/api/kubernetes/deploy', {
      method: 'POST',
      body: JSON.stringify(requestBody)
    });
  }
};

// Release相关API
export const releaseApi = {
  // 获取Release列表（分页）
  getReleases: async (page = 1, size = 10, projectId = null, moduleId = null, envType = null, clusterId = null, namespace = null, releaseName = null, projectGroupId = null) => {
    // 使用新的关联查询接口
    let url = `/api/release/page/with-project-info?page=${page}&size=${size}`;
    if (projectId) url += `&projectId=${projectId}`;
    if (moduleId) url += `&moduleId=${moduleId}`;
    if (envType) url += `&envType=${envType}`;
    if (clusterId) url += `&clusterId=${clusterId}`;
    if (namespace) url += `&namespace=${namespace}`;
    if (releaseName) url += `&releaseName=${encodeURIComponent(releaseName)}`;
    if (projectGroupId) url += `&projectGroupId=${projectGroupId}`;
    // 使用新接口不需要再添加这些参数，因为已经内置了关联查询
    // url += `&includeProject=true&includeProjectGroup=true`;
    console.log('调用Release API URL:', `${API_BASE_URL}${url}`);
    return request(url);
  },

  // 获取Release详情
  getRelease: async (id) => {
    return request(`/release/${id}`);
  },

  // 删除Release
  deleteRelease: async (id) => {
    return request(`/release/${id}`, {
      method: 'DELETE'
    });
  }
};
